<?php
namespace app\faxing\channel;


use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Souyouji extends FaXingBase
{

    public function register($params)
    {
        $cid = $this->cid;
        ;


        if(!$this->check_sign($params,$this->extdata['APPKEY'])){
            $this->error("签名错误");
        }

        $account = $cid."_".$params['uid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $this->cid;
            $data['gid'] = $this->gid;
            $data['is_age'] = 0;

            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        $player['third_data'] = $params;
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);

        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];

    }


    public function order($order)
    {
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();
        $token = get_encrypt($order['uid']);

        $redis = new Redis();
        $player = $redis->get($token);

        $third_data = $player['third_data'];

        $account = $player['account'];
        $account = explode("_",$account);
        $sign = get_sign(['order_no'=>$order['order_no']],$this->extdata['APPKEY']); // 回传验证
        $time = time();
        $data = [
            'uid' => $account[1],
            'ext' => $third_data['ext'],
            'nonce' => get_noncestr(),
            'time' => $time,
            'serverid' => $role['sid'],// 区服id
            'server_name'=> $role['sid'],//区服id
            'roleid' => $role['role_id'],// 角色id
            'role_name' => $role['role_name'],// 角色名称
            'money'=> $order['amount'] * 100,//金额 整数：分
            'propsname'=>$order['goods_name'],//商品名称
            'order' => $order['order_no'],// 订单号
            'token'=> $sign, // 回传验证
        ];
        $data['sign'] = $this->signData($data,$this->extdata['APPKEY']);;
        $url = "https://api.sooyooj.com/index/pay/401?";
        return $url.urldecode(http_build_query($data));
    }

    public function check_order($params)
    {
        $order_no = $params['order'];

        $sign = $params['token'];

        // 双重校验
        $order_sign = get_sign(['order_no'=>$order_no],$this->extdata['APPKEY']);

        if($order_sign != $sign){
            echo json_encode(['code'=>403,'message'=>'签名错误']);exit;
        }

        if(!$this->check_sign($params,$this->extdata['APPKEY'])){
            echo json_encode(['ReturnCode'=>-1,'message'=>'签名错误']);exit;
        }

        // 查询订单
        $order = Order::where([
            'order_no'=>$order_no
        ])->find();
        
        if($order['amount'] * 100 != $params['money']){
            echo json_encode(['code'=>-2,'message'=>'处理失败']);exit;
        }

        $order->trade_no = $this->cid."_".$params['order'];
        $order->save();

        return $order;
    }

    public function create_role($params)
    {
        $url = "https://api.sooyooj.com/index/role/401?";

        $redis = new Redis();
        $player = $redis->get($params['token']);
        $third_data = $player['third_data'];
        $account = explode("_",$player['account']);
        $time = time();
        $data = [
            'uid' => (int) $account[1],
            'nonce' => get_noncestr(32),
            'time' => $time,
            'serverid' =>(int) $params['sid'],
            'server_name' => $params['sid'],
            'roleid' => $params['role_id'],
            'role_name' =>  $params['role_name'],
            'level'=> $params['role_level'],
        ];
        $data['sign'] = $this->signData($data,$this->extdata['APPKEY']);

        $res = file_get_contents($url.urldecode(http_build_query($data)));
        echo $res;exit;
    }


    public function message($message,$order)
    {
        echo $message === 'success' ? json_encode(['ReturnCode'=>0,'message'=>'成功']) :  json_encode(['code'=>'-1','message'=>'处理失败']);
        exit;
    }

    private function signData($data, $secret) {
        ksort($data);
        foreach ($data as $k => $v) {
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp) . $secret;

        return md5($str);
    }

    protected function check_sign($params, $key)
    {
        $sign = $params['sign'];
        unset($params['gid']);
        unset($params['cid']);
        unset($params['sign']);
        $check_sign = $this->signData($params,$key);

        if($check_sign != $sign){
            return false;
        }
        return true;
    }

}